# camera_client.py

import requests
import time
from typing import List, Dict
# from config import CAMERA_API_URL, REPORT_API_URL, API_TOKEN, REQUEST_TIMEOUT, MAX_RETRIES
from configs import get_config
import json

def fetch_camera_list() -> List[Dict]:
    """
    从外部系统获取待分析的摄像头列表
    """
    # # 测试环境返回模拟数据
    # return {'id': 'cameraId',
    #         #  'rtsp': 'test/video/huning2.mp4',
    #          'rtsp': 'test/video/test_video.mp4',
    #          'name': 'name',
    #          'district':'district',
    #          'location':'latitude,longitude'
    #         }
    
    # 真实环境请求外部 API
    config = get_config()
    CAMERA_API_URL = config['api']['camera_api_url']
    API_TOKEN = config['api']['api_token']
    
    MAX_RETRIES = 3
    REQUEST_TIMEOUT = 10
    
    headers = {
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    }

    for i in range(MAX_RETRIES):
        try:
            print(f"📡 正在请求摄像头列表... ({i+1}/{MAX_RETRIES})")
            response = requests.get(
                CAMERA_API_URL,
                headers=headers,
                timeout=REQUEST_TIMEOUT
            )
            if response.status_code == 200:
                data = response.json()
                return  data.get('data', {}) # json.loads(data)
                # cameras = []
                # for item in data.get('data', []):
                #     if all(k in item for k in ['cameraId', 'rtspUrl']):
                #         cameras.append({
                #             'id': item['cameraId'],
                #             'rtsp': item['rtspUrl'],
                #             'name': item.get('name', ''),
                #             'district': item.get('district', 'unknown'),
                #             'location': (item.get('latitude'), item.get('longitude'))
                #         })
                # print(f"✅ 成功获取 {len(cameras)} 路摄像头")
                # return cameras[:20]  # 只取前 20 路
            else:
                print(f"❌ 请求失败: {response.status_code} {response.text}")
        except Exception as e:
            print(f"⚠️ 请求异常: {e}")
            if i < MAX_RETRIES - 1:
                time.sleep(2 ** i)
            continue
    return {}
    # raise Exception("❌ 无法从外部系统获取摄像头列表")



def report_event(data: Dict):
    """
    上报事件到外部系统
    """
    
    config = get_config()
    url = config['api']['report_api_url']
    headers = {
        "Authorization": f"Bearer {config['api']['api_token']}",
        "Content-Type": "application/json"
    }

    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        print(f"✅ 事件上报成功: {response.json()}")
    else:
        print(f"❌ 事件上报失败: {response.status_code} {response.text}")
        